#include "baidulpr.h"
#include <QCoreApplication>
#include <QBuffer>

BaiduLPR::BaiduLPR(QObject *parent) : QObject(parent)
{
    /* 创建一个可以发起HTTP请求的管理器 */
    networkAccessManager = new QNetworkAccessManager(this);

    /* 获取自己的tokken */
    //MytokenUrl = QString(GettokenApi).arg(MyApiKey).arg(MySecretKey);
    GettokneUrl = "24.e16ee14bcc22c25c65e4c65cfedad7fa.2592000.1668772255.282335-27284053";
    masktokenUrl = "24.eed565cba9632ad1f92320aa71014320.2592000.1668772894.282335-27464037";

    /* 创建接受报文变量 */
    QByteArray requestData;
    requestData.clear();

    //requestNetwork(MytokenUrl,requestData);
}

void BaiduLPR::requestNetwork(QString Url, QByteArray requestData)
{
    /* 网络请求 */
    QNetworkRequest networkRequest;

    /* 开发板需要加一些安全配置才能访问https */
    QSslConfiguration config;
    config.setPeerVerifyMode(QSslSocket::VerifyNone);
    config.setProtocol(QSsl::TlsV1SslV3);
    networkRequest.setSslConfiguration(config);

    networkRequest.setHeader(QNetworkRequest::ContentTypeHeader,"application/json;charset=UTF-8");

    /* 设置Header参数值为application/x-www-form-urlencoded */
    networkRequest.setRawHeader("Content-Type", QString("application/x-www-form-urlencoded").toLatin1());

    /* 设置访问的地址 */
    networkRequest.setUrl(Url);

    QNetworkReply *newReply = networkAccessManager->post(networkRequest, requestData);
    connect(newReply,SIGNAL(finished()),this,SLOT(rlyFinished()));
    connect(newReply,SIGNAL(readyRead()),this,SLOT(readyReadData()));
}

QString BaiduLPR::getJsonValue(QByteArray ba, QString key)
{
    QJsonParseError parseError;
    QJsonDocument jsonDocument = QJsonDocument::fromJson(ba, &parseError);

    if (parseError.error == QJsonParseError::NoError) {

        if (jsonDocument.isObject()) {
            /* jsonDocument转化为json对象 */
            QJsonObject jsonObj = jsonDocument.object();

            if (jsonObj.contains(key)) {
                QJsonValue jsonVal= jsonObj.value(key);

                if (jsonVal.isString()) {
                    return jsonVal.toString();

                } else if (jsonVal.isArray()) {
                    /* 转换成jsonArray */
                    QJsonArray arr = jsonVal.toArray();
                    /* 获取第一个元素 */
                    QJsonValue jv = arr.at(0);
                    return jv.toString();
                }
            }
        }
    }
    return nullptr;
}

QString BaiduLPR::getJsonValue(QByteArray ba, QString key1, QString key2)
{
    QJsonParseError parseError;
    QJsonDocument jsonDocument = QJsonDocument::fromJson(ba, &parseError);

    if (parseError.error == QJsonParseError::NoError) {

        if (jsonDocument.isObject()) {
            /* jsonDocument转化为json对象 */
            QJsonObject jsonObj = jsonDocument.object();
            if (jsonObj.contains(key1)) {
                QJsonObject jsonArrObj = jsonObj.value(key1).toObject();
                if (jsonArrObj.contains(key2)) {
                    return jsonArrObj.value(key2).toString();
                } else { qDebug() << "not contains " + key2 << endl;}
            } else { qDebug() << "not contains " + key1 << endl;}
        } else { qDebug() << "is not an Object" << endl;}
    }

    return nullptr;
}

QString BaiduLPR::GetMaskValue(QByteArray ba)
{
    QJsonParseError parseError;
    QJsonDocument jsonDocument = QJsonDocument::fromJson(ba, &parseError);
    if(parseError.error == QJsonParseError::NoError){
        QJsonObject jsonObj = jsonDocument.object();
        if(jsonObj.contains("person_info")){
            QJsonValue value = jsonObj.value("person_info");
            QJsonObject jsonArrObj = value.toArray().at(0).toObject();
            if(jsonArrObj.contains("attributes")){
                QJsonValue attributes = jsonArrObj.value("attributes");
                QJsonObject face_mask = attributes.toObject();
                if(!face_mask.isEmpty()){
                    QJsonObject face_mask_Reslue = face_mask.value("face_mask").toObject();
                    return face_mask_Reslue.value("name").toString();
                }
            }
        }
    }
    return "error";
}

void BaiduLPR::ready2OCR(QString imagePath)
{
    if(GettokneUrl.isEmpty()){
        qDebug()<< "没有鉴权码！" <<endl;
        return;
    }
    GetOCRResult(imagePath);
}

void BaiduLPR::rlyFinished()
{
    QNetworkReply *reply = (QNetworkReply *)sender();
    reply->deleteLater();
    reply = nullptr;
}

void BaiduLPR::readyReadData()
{
    QNetworkReply *reply = (QNetworkReply *)sender();

    QByteArray Data = reply->readAll();

    if (reply->url() == QUrl(serverApiUrl)) {
        qDebug()<<QString(Data)<<endl;
        QString key1 = "words_result";
        QString key2 = "number";
        QString temp = getJsonValue(Data, key1,key2);
        qDebug()<< "车牌识别结果为：" << temp<<endl;
        if(temp.isEmpty()){
            qDebug()<< "识别失败" << endl;

        }
        else{
            emit this->GetLRPData(temp); // 显示
            emit this->CarIDTTS(QString("https://tts.youdao.com/fanyivoice?word=%1&le=zh&keyfrom=speaker-target").arg(temp));//下载音频
            emit this->seedsqldata("CarID:" + temp);//数据库入库
        }
    }

    if (reply->url() == QUrl(serverApiUrl2)) {
        qDebug()<< QString(Data) <<endl;
        QString maskResult = GetMaskValue(Data);
        qDebug()<< maskResult <<endl;
        if(maskResult == "无口罩"){
            emit this->TTS_CMD("/bishe/yuyin/no_mask.wav");//语音播报
            emit this->seedsqldata("Mask:" + maskResult);
        }
        else{
            emit this->seedsqldata("Mask:" + maskResult);//数据库入库
        }

    }
}

void BaiduLPR::GetOCRResult(QString filename)
{
    QFile file;
    file.setFileName(filename);
    if (!file.exists()) {
        qDebug()<<filename<<"不存在!"<<endl;
        return;
    }
    QByteArray requestData;
    file.open(QIODevice::ReadOnly);
    requestData = file.readAll();
    file.close();
    /* Img to base64 */
    QByteArray imgbase64 = requestData.toBase64().toPercentEncoding();
    QByteArray body = "image=" + imgbase64;

    serverApiUrl = QString(BaiduLPRApi).arg(GettokneUrl);
    //qDebug()<< body <<endl;
    requestNetwork(serverApiUrl,body);
}

void BaiduLPR::GetMaskResult(QString filename)
{
    QFile file;
    file.setFileName(filename);
    if (!file.exists()) {
        qDebug()<<filename<<"不存在!"<<endl;
        return;
    }
    QByteArray requestData;

    file.open(QIODevice::ReadOnly);
    requestData = file.readAll();
    file.close();

    /* Img to base64 */
    QByteArray imgbase64 = requestData.toBase64().toPercentEncoding();
    QByteArray body = "image=" + imgbase64 + "&type=face_mask";

    serverApiUrl2 = QString(BaiduMaskApi).arg(masktokenUrl);
    //qDebug()<< body <<endl;
    requestNetwork(serverApiUrl2,body);
}

